package com.itheima.filter;

import cn.hutool.core.util.StrUtil;
import com.itheima.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

//@WebFilter("/*")       //演示拦截器，先注释其连接路径
public class TokenFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
//        1.强转请求对象和响应对象
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

//        2.获取请求路径
        String url = req.getRequestURL().toString();

//        3.路径中包含login的放行，其他的校验
        if(url.contains("login")){
            chain.doFilter(request, response);
            return;         //防止代码往下执行
        }

//        4.校验Token,第一步看有没有Token
        String jwt = req.getHeader("token");        //不区分大小写，token和Token都行


//        5.为空响应401
        if(StrUtil.isEmpty(jwt)){
            res.setStatus(HttpServletResponse.SC_UNAUTHORIZED);     //报错，返回401
            return;
        }

//        6.不为空校验,错了抛异常，没错登陆成功
        try {
            JwtUtils.parseJWT(jwt);
            chain.doFilter(request, response);       //放行,加入Controller层
        } catch (Exception e) {
            e.printStackTrace();
            res.setStatus(HttpServletResponse.SC_UNAUTHORIZED);         //报错，返回401
        }


    }
}
